//
//  JJImagePickerController.swift
//  JJImagePicker
//
//  Created by 李加建 on 2021/5/31.
//

import UIKit

class ImagePickerController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        setNavi()

        viewModel.fetchAssetCollections()
        collectionView.reloadData()
        updateTitleButton()
    }

    var manager: ImagePickerManager

    init(manager: ImagePickerManager) {
        self.manager = manager
        super.init(nibName: nil, bundle: nil)
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

//    weak var delegate: ImagePickerDelegate?

    private lazy var viewModel = ImagePickerViewModel()

    private lazy var collectionView: UICollectionView = {
        var lineCount = CGFloat(manager.lineCount)
        if lineCount <= 0 {
            lineCount = 4.0
        }
        let layout = UICollectionViewFlowLayout()
        let width: CGFloat = (view.frame.width - (lineCount - 1) * 2) / lineCount
        layout.minimumLineSpacing = manager.lineSpacing
        layout.minimumInteritemSpacing = manager.lineSpacing
        layout.itemSize = CGSize(width: width, height: width)
        layout.scrollDirection = .vertical
        let lazy = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        lazy.delegate = self
        lazy.dataSource = self
        lazy.backgroundColor = .clear
        lazy.showsVerticalScrollIndicator = false
        lazy.showsHorizontalScrollIndicator = false

        lazy.register(AssetCell.classForCoder(), forCellWithReuseIdentifier: "AssetCell")

        return lazy
    }()

    lazy var backgroundButton: UIButton = {
        let lazy = UIButton(frame: view.bounds)
        return lazy
    }()

    private lazy var tipLabel: UILabel = {
        let lazy = UILabel()
        lazy.font = UIFont(name: "PingFangSC-Medium", size: 15)
        lazy.textColor = .white
        lazy.text = "选择一张图片"
        return lazy
    }()

    private lazy var titleButton: UIButton = {
        let lazy = UIButton()
//        lazy.setTitle("最近项目", for: .normal)
        lazy.setTitleColor(.white, for: .normal)
        lazy.titleLabel?.font = UIFont(name: "PingFangSC-Semibold", size: 19)
        lazy.sizeToFit()
        lazy.contentHorizontalAlignment = .left
        lazy.addTarget(self, action: #selector(titleButtonAction), for: .touchUpInside)
        return lazy
    }()

    private lazy var collectionAssetView: AlbumSelectedView = {
        let lazy = AlbumSelectedView(viewModel: viewModel)
        lazy.didSelectedBlock = { [weak self] in
            self?.collectionView.reloadData()
            self?.updateTitleButton()
        }
        lazy.indicatorView = self.arrawImageView
        return lazy
    }()

    private lazy var arrawImageView: UIImageView = {
        let lazy = UIImageView()
        lazy.image = UIImage.createImage(base64String: imageBase64String)
        return lazy
    }()

    override var preferredStatusBarStyle: UIStatusBarStyle {
        .lightContent
    }

    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        updateSafeArea()
    }
}

private extension ImagePickerController {
    func setup() {
        backgroundButton.backgroundColor = UIColor.black
        view.addSubview(backgroundButton)
        view.addSubview(collectionView)
        view.addSubview(tipLabel)
    }

    func setNavi() {
        let attributes: [NSAttributedString.Key: Any] = [
            NSAttributedString.Key.foregroundColor: UIColor.black,
            NSAttributedString.Key.font: UIFont(name: "PingFangSC-Semibold", size: 18) as Any,
        ]
        navigationController?.navigationBar.titleTextAttributes = attributes
        let image = UIImage.createImage(color: .clear, size: CGSize(width: 44, height: 44))
        navigationController?.navigationBar.isTranslucent = true
        navigationController?.navigationBar.setBackgroundImage(image, for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.backgroundColor = .clear

        let backItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(backItemAction))
        backItem.tintColor = .white
        navigationItem.leftBarButtonItem = backItem

        navigationItem.titleView = titleButton

        titleButton.addSubview(arrawImageView)
        arrawImageView.frame = CGRect(x: 0, y: 0, width: 16, height: 16)
    }

    @objc
    func backItemAction() {
        dismiss(animated: true, completion: nil)
    }

    @objc
    func titleButtonAction() {
        if collectionAssetView.isShow {
            collectionAssetView.hide()
        } else {
            collectionAssetView.show(in: view)
        }
    }

    func updateTitleButton() {
        titleButton.setTitle(viewModel.selectedAlbum?.name, for: .normal)
        titleButton.sizeToFit()
        let point = CGPoint(x: titleButton.frame.width, y: titleButton.frame.height / 2 - 8)
        arrawImageView.frame = CGRect(origin: point, size: CGSize(width: 16, height: 16))
        var rect = titleButton.frame
        rect.size.width += 16
        titleButton.frame = rect
    }

    func updateSafeArea() {
        let height = view.frame.height - view.safeAreaInsets.top
        let point = CGPoint(x: 0, y: view.safeAreaInsets.top)
        let size = CGSize(width: view.frame.width, height: height - view.safeAreaInsets.bottom - 66)
        collectionView.frame = CGRect(origin: point, size: size)
        tipLabel.frame = CGRect(x: 20, y: collectionView.frame.maxY + 17, width: 200, height: 22)
        collectionAssetView.frame = CGRect(x: 0, y: view.safeAreaInsets.top, width: view.frame.width, height: height)
    }
}

extension ImagePickerController: UICollectionViewDataSource, UICollectionViewDelegate {
    public func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        viewModel.count
    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell: AssetCell = collectionView.dequeueReusableCell(withReuseIdentifier: "AssetCell", for: indexPath)
            as? AssetCell else { fatalError("AssetCell") }
        cell.backgroundColor = .white
        cell.asset = viewModel.asset(for: indexPath.row)

        return cell
    }

    public func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        viewModel.selectedAsset(index: indexPath.row) { [weak self] result in
            guard let image = try? result.get() else { return }
            guard let self = self else { return }
            if self.manager.allowsEditing {
                self.manager.editImage = image
                let next = ImageCutController(manager: self.manager)
                self.navigationController?.pushViewController(next, animated: true)
            } else {
                self.manager.delegate?.didSeletedImage(image)
            }
        }
    }
}

extension ImagePickerController: UICollectionViewDelegateFlowLayout {
    func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, referenceSizeForFooterInSection _: Int) -> CGSize {
        CGSize(width: view.frame.width, height: 0)
    }

    func collectionView(_: UICollectionView, layout _: UICollectionViewLayout, referenceSizeForHeaderInSection _: Int) -> CGSize {
        CGSize(width: view.frame.width, height: 20)
    }
}
